<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :loading="loading"
    :helpMessage="t('modal.helpMessage')"
    width="800px"
    :minHeight="420"
    :title="getTitle"
    :okText="t('modal.confirm')"
    :cancelText="t('modal.cancel')"
    @ok="handleSubmit"
  >
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            field="name"
            :label="t('searchTable.columns.name_role')"
            :rules="[{ required: true, message: t('modal.please.write.name_role') }]"
            style="margin-bottom: 15px"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              v-model="formData.name"
              :placeholder="t('modal.please.write.name_role')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="code"
            :label="t('searchTable.columns.code')"
            :rules="[
              {
                required: true,
                message: t('modal.please.write.code'),
              },
            ]"
            :validate-trigger="['change', 'blur']"
            style="margin-bottom: 15px"
          >
            <a-input
              v-model="formData.code"
              :placeholder="t('modal.please.write.code')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="sort"
            :label="t('searchTable.columns.sort')"
            style="margin-bottom: 15px"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              v-model="formData.sort"
              :placeholder="t('modal.please.write.sort')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="remark"
            :label="t('searchTable.columns.remark')"
            style="margin-bottom: 15px"
            :validate-trigger="['change', 'blur']"
          >
            <a-textarea
              allow-clear
              v-model="formData.remark"
              :placeholder="t('modal.please.write.remark')"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import useLoading from '@/hooks/loading';
  import { useI18n } from 'vue-i18n';
  import { cloneDeep } from 'lodash-es';
  //company
  import { add, update } from '@/api/systemManage/role';
  import { Message } from '@arco-design/web-vue';

  export default defineComponent({
    name: 'AddBook',
    components: { BasicModal },
    emits: ['success'],
    setup(_, { emit }) {
      const { t } = useI18n();
      const isUpdate = ref(false);
      //表单
      const formRef = ref<FormInstance>();
      //表单字段
      const basedata = {
        id: 0,
        name: '',
        remark: '',
        sort: '',
        code: '',
      };
      const formData = ref(basedata);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(
        async (data) => {
          //清空上次表单内容
          formRef.value?.resetFields();
          //关闭 loading 状态：
          setModalProps({ confirmLoading: false });
          //异步拉取下拉选项数据
          //判断是否是编辑
          isUpdate.value = !!data?.isUpdate;
          if (unref(isUpdate)) {
            formData.value = cloneDeep(data.record);
          } else {
            formData.value = basedata;
          }
        }
      );
      const getTitle = computed(() =>
        !unref(isUpdate) ? t('modal.add') : t('modal.edit')
      );
      //点击确认
      const { loading, setLoading } = useLoading();
      const handleSubmit = async () => {
        try {
          const res = await formRef.value?.validate();
          if (!res) {
            setLoading(true);
            if (isUpdate.value) {
              Message.loading({
                content: t('searchTable.message.loading.updating'),
                id: 'upStatus',
              });
              await update(unref(formData));
              Message.success({
                content: t('searchTable.message.loading.update.successful'),
                id: 'upStatus',
              });
            } else {
              Message.loading({
                content: t('searchTable.message.loading.adding'),
                id: 'upStatus',
              });
              await add(unref(formData));
              Message.success({
                content: t('searchTable.message.loading.add.successful'),
                id: 'upStatus',
              });
            }

            closeModal();
            emit('success');
            setLoading(false);
          }
        } catch (error) {
          setLoading(false);
          Message.clear('top');
        }
      };

      interface ApiOption {
        value: string;
        title: string;
      }

      const apiGroupOptions = computed<ApiOption[]>(() => [
        { value: 'GET', title: t('modal.options.api.method.get') },
        { value: 'POST', title: t('modal.options.api.method.post') },
        { value: 'PUT', title: t('modal.options.api.method.put') },
        { value: 'DELETE', title: t('modal.options.api.method.delete') },
      ]);

      return {
        registerModal,
        getTitle,
        handleSubmit,
        formRef,
        loading,
        formData,
        t,
        apiGroupOptions,
        isUpdate,
      };
    },
  });
</script>
